<template>
  <div>
    <a-upload
      v-if="!!uploadList || !isUpload"
      name="file"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :disabled="loading"
      :multiple="multiple"
      @change="handleChanges"
    >
      <!--@change="handleUpload">-->
      <a-button
        v-if="isShow"
        icon="upload"
        :loading="loading"
        type="primary"
        style="margin-bottom: 20px"
        @click="files = []"
      > 上传 </a-button>
      <!--<div>支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>-->
    </a-upload>
    <a-button
      v-if="isDelete"
      type=""
      style="margin-bottom: 20px; margin-left: 20px"
    >
      <a-icon style="font-size: 1.2rem" />
      删除
    </a-button>
    <a-table
      :pagination="false"
      row-key="id"
      :columns="columnAssment"
      :data-source="dataAssement"
      :loading="loading"
    >
      <span
        slot="serial"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <span
        slot="action"
        slot-scope="text, record"
      >
        <a
          v-if="!checkVisibleInDetail"
          href="javascript:"
          @click="handleExportLimit"
        >导出</a>
        <a
          v-else
          :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId"
          target="_parent"
        >导出</a>
        <a-divider type="vertical" />
        <a
          href="javascript:"
          @click="$filePreview(record)"
        >查看</a>
        <a-divider
          v-if="isShow && (!!deleteUrl || !isUpload)"
          type="vertical"
        />
        <a
          v-show="isShow && (!!deleteUrl || !isUpload)"
          @click="() => deleteFile(record)"
        >删除</a>
      </span>
    </a-table>
  </div>
</template>

<script>
import { checkVisibleInDetail } from '@/utils/util'
import Vue from 'vue'
import { downZip, uploadFile, uploadFileToCenter } from '@/api'
import { getUploadPathByBusinessCode } from '@/api/commons'
import download from 'downloadjs'
import debounce from 'lodash/debounce'

const columnAssment = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: 80,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName'
  },
  {
    title: '附件格式',
    ellipsis: true,
    dataIndex: 'suffixName'
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'Utable',
  components: {},
  props: {
    text: String,
    listUrl: {
      type: String,
      value: ''
    },
    reqMethod: {
      type: String,
      value: '',
      default: 'get'
    },
    isDelete: {
      type: Boolean,
      default: false
    },
    // 文件上传后是否回调
    isUpload: {
      type: Boolean,
      default: true
    },
    // 业务上传接口
    uploadList: {
      type: String,
      value: ''
    },
    // 业务上传删除
    deleteUrl: {
      type: String,
      value: ''
    },
    // 业务主表id
    businessId: {
      type: String,
      value: ''
    },
    // 模块code
    businessCode: {
      type: String,
      value: ''
    },
    isShow: {
      type: Boolean,
      default: true
    },
    uploadArrys: {
      type: Array,
      default: () => []
    },
    ifStopWork: {
      type: Boolean,
      default: false
    },
    ifStopConstruction: {
      type: Boolean,
      default: false
    },
    // 是否需要在上传后，请求文件列表接口刷新
    refreshAfterUpload: {
      type: Boolean,
      default: true
    },
    useChinese: {
      type: Boolean,
      default: false
    },
    // 默认多选开启
    multiple: {
      type: Boolean,
      default: () => true
    },
    // 可上传数量
    count: {
      type: [String, Number],
      default() {
        return 100
      }
    }
  },
  watch: {
    uploadArrys: {
      handler(nv) {
        this.dataAssement = [...this.uploadArrys]
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      loading: false,
      columnAssment,
      uploadFile: {},
      dataAssement: [],
      deleteObj: {},
      token: '',
      // 一次最多10个
      num: 10,
      // 文件列表
      files: []
    }
  },
  created() {
    if (this.listUrl && this.listUrl.trim() !== '') {
      this.getFile()
    }
    this.token = Vue.getAcloudProvider().getAccessToken()
  },
  methods: {
    handleExportLimit() {
      this.$message.warning('抱歉，app端无法导出，请在系统电脑端进行导出')
    },
    beforeUpload(info) {
      // const { size } = info
      // if (size / 1024 / 1024 > 500) {
      //   // 限制文件大小为500M
      //   this.$message.error('上传文件不可超出500M')
      //   this.uploadFile = null
      //   return false
      // }
      // this.uploadFile = info
      return false
    },
    /**
     * @description: 文件获取防抖
     * @param {function}
     * @return {void}
     */
    getFile: debounce(function () {
      this.getUploadFile()
    }, 200),
    getUploadFile() {
      const data = { businessId: this.businessId }
      if (this.businessId != null && this.businessId != '') {
        this.loading = true
        if (this.reqMethod === 'get') {
          this.loading = false
          this.$axios
            .get(this.listUrl, { params: data })
            .then((res) => {
              if (res.code === 200) {
                this.dataAssement = res.data
              }
              setTimeout(() => {
                this.loading = false
              }, 0)
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          // if(_this.ifStopWork == true){
          //   _this.deleteObj.stopFileIds = [record.commonId]
          // }else if(_this.ifStopConstruction== true){
          //   _this.deleteObj.startFileIds =  [record.commonId]
          // }else{
          //   _this.deleteObj.commonFileId = record.commonId
          // }

          this.$axios
            .post(this.listUrl, data)
            .then((res) => {
              // this.$axios.post(this.listUrl,{params:{businessId:this.businessId}}).then(res=>{
              if (res.code == 200 || res.data.code == 200) {
                console.log('返回数据：', res.data)
                let arr = res.data || res.data.data
                if (arr.length > 0) {
                  this.dataAssement = res.data
                } else {
                  this.dataAssement = []
                }
              }
              setTimeout(() => {
                this.loading = false
              }, 0)
            })
            .catch(() => {
              this.loading = false
            })
        }
      }
    },
    handleUpload() {
      const that = this
      //根据业务编码获取上传目录
      getUploadPathByBusinessCode(this.businessCode).then((res) => {
        const { catalog } = res.data
        const data = new FormData()
        data.append('file', that.uploadFile)
        data.append('path', catalog)
        //描述信息
        data.append('desc', '')
        //上传文件到文件中心，无业务ID
        that.loading = true
        uploadFileToCenter(data)
          .then((response) => {
            // if(res.code == 200 || res.data.code == 200){
            that.loading = false

            that.dataAssement = that.dataAssement.concat(response.data)
            that.$emit('fileArrysData', that.dataAssement)
            // }
          })
          .catch(() => {
            that.loading = false
          })
      })
    },
    /**
     * @description: 附件名弹窗提示
     * @param {void}
     * @return {function}
     */
    nameDebounce: debounce(function () {
      this.$confirm({
        title: '提示',
        content: this.errorTips ? this.errorTips : '请规范附件名称，附件名称中需含有汉字',
        okType: 'danger'
      })
    }, 500),
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function () {
      this.handleUploadFun()
    }, 500),
    /**
     * @description: 上传
     * @return {void}
     */
    async handleUploadFun() {
      let pass = true
      if (pass && this.dataAssement.length + this.files.length > this.count) {
        pass = false
        this.$message.error(`最多上传${this.count}个文件！`)
        this.files = this.files.slice(0, this.count - this.dataAssement.length)
      }
      if (this.multiple) {
        if (pass && this.files.length > this.num) {
          this.$message.error(`一次最多上传${this.num}个文件！`)
          this.files = this.files.slice(0, this.num)
        }
      }
      this.loading = true
      // 防止上传错误一直loading
      try {
        for (let i = 0; i < this.files.length; i++) {
          await this.uploadFun(this.files[i])
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.files = []
        this.loading = false
      }
    },
    /**
     * @description: 接管文件上传
     * @param {object} info 文件对象
     * @return {void}
     */
    handleChanges(info) {
      let pass = true
      const { file } = info
      if (file.size / 1024 / 1024 > 500) {
        // 附件大小校验
        // 限制文件大小为500M
        this.sizeDebounce()
        pass = false
      }
      if (this.useChinese) {
        // 附件名称需要汉字校验
        let re = new RegExp('[\u4E00-\\u9FFF]+', 'g')
        if (!re.test(file.name)) {
          this.nameDebounce()
          pass = false
        }
      }
      if (pass) {
        this.files.push(file)
        this.fileChange()
      }
    },
    /**
     * @description: 上传函数拆分
     * @param {object} file 文件
     * @return {void}
     */
    uploadFun(file) {
      return new Promise(async (resolve, reject) => {
        setTimeout(() => {
          this.loading = false
        }, 3000)
        let that = this
        const data = new FormData()
        data.append('file', file)
        data.append('businessCode', this.businessCode)
        let arr = []
        const res = await uploadFile(data)
        // debugger
        if (res.code == 200) {
          // let  obj = {}
          // obj.fileName = res.data.fileName
          // obj.fileType =  res.data.fileType
          // obj.url =  res.data.url
          arr.push(res.data)
          that.dataAssement = that.dataAssement.concat(arr)
          // debugger

          if (that.businessId != '' && that.businessId != undefined) {
            let data = { businessId: that.businessId, commonFileId: res.data.commonId }
            if (that.ifStopWork == true) {
              data = { businessId: that.businessId, stopFileIds: [res.data.commonId] }
            } else if (that.ifStopConstruction == true) {
              data = { businessId: that.businessId, startFileIds: [res.data.commonId] }
            } else {
              data = { businessId: that.businessId, commonFileId: res.data.commonId }
            }
            console.log('上传')
            await that.$axios.post(that.uploadList, data)
            let uploadArr = Array.from(new Set(that.dataAssement))
            this.$emit('fileArrysData', uploadArr)
            this.refreshAfterUpload && this.getUploadFile()
          } else {
            if (that.$listeners['update:fileArrys']) {
              that.$emit('update:fileArrys', that.dataAssement)
            }
            that.$emit('fileArrysData', that.dataAssement)
          }
        }
        resolve()
      })
    },
    deleteFile(record) {
      const _this = this
      _this.$confirm({
        title: '删除',
        content: '确定删除附件吗？',
        onOk() {
          return new Promise((resolve, reject) => {
            console.log(_this.businessId, _this.businessCode, record.commonId)
            if (_this.businessId != '' && _this.businessId != undefined) {
              _this.deleteObj.businessId = _this.businessId
              _this.deleteObj.code = _this.businessCode

              if (_this.ifStopWork == true) {
                _this.deleteObj.stopFileIds = [record.commonId]
              } else if (_this.ifStopConstruction == true) {
                _this.deleteObj.startFileIds = [record.commonId]
              } else {
                _this.deleteObj.commonFileId = record.commonId
              }

              _this.$axios
                .post(_this.deleteUrl, _this.deleteObj)
                .then((res) => {
                  if (res.data && res.data.code === 200) {
                    _this.$message.success('删除成功')
                    _this.getUploadFile()
                    resolve(res)
                  } else {
                    _this.$message.error('删除失败')
                    reject()
                  }
                })
                .catch(() => {
                  reject()
                })
            } else {
              _this.dataAssement.forEach(function (obj, i) {
                if (obj.commonId == record.commonId) {
                  _this.dataAssement.splice(i, 1)
                  _this.$message.success('删除成功！')
                }
              })
              if (_this.$listeners['update:fileArrys']) {
                _this.$emit('update:fileArrys', _this.dataAssement)
              }
              _this.$emit('fileArrysData', _this.dataAssement)
              reject()
            }
          }).catch(() => {})
        },
        onCancel() {}
      })
    }
  }
}
</script>

<style scoped>
</style>
